package com.example.chengzhengwei;

import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;

import com.example.chengzhengwei.utils.SpectrophotometerProtocol;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.formatter.ValueFormatter;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

public class FullScreenRunActivity extends AppCompatActivity {
    private LineChart chart;
    private List<RunData> runDataList;
    private int samplePeriod = 15; // 默认采样周期15秒
    private final int[] channelColors = {
            0xFF0000FF, // 通道1：蓝色
            0xFFFF00FF, // 通道2：粉色
            0xFF00FF00, // 通道3：绿色
            0xFFFFFF00, // 通道4：黄色
            0xFF00FFFF, // 通道5：青色
            0xFF000080, // 通道6：深蓝色
            0xFF800080, // 通道7：紫色
            0xFF808000  // 通道8：橄榄绿
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_run_fullscreen);

        // 全屏显示
        getWindow().getDecorView().setSystemUiVisibility(
                View.SYSTEM_UI_FLAG_FULLSCREEN
                        | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                        | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);

        // 初始化返回按钮
        ImageButton btnBack = findViewById(R.id.btn_back);
        btnBack.setOnClickListener(v -> finish()); // 点击关闭当前界面

        // 获取传递的数据
        runDataList = (List<RunData>) getIntent().getSerializableExtra("runDataList");
        samplePeriod = getIntent().getIntExtra("samplePeriod", 15);

        // 初始化图表
        chart = findViewById(R.id.chart);
        initializeFullScreenChart();
    }

    private void initializeFullScreenChart() {
        // 1. 基本配置
        chart.getDescription().setEnabled(false);
        chart.setDrawGridBackground(false);
        chart.setTouchEnabled(true);
        chart.setDragEnabled(true);
        chart.setScaleEnabled(true);
        chart.setPinchZoom(true);

        // 2. 禁用图例（全屏显示不需要）
        Legend legend = chart.getLegend();
        legend.setEnabled(false);

        // 3. 配置X轴
        XAxis xAxis = chart.getXAxis();
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setGranularity(1f);
        xAxis.setDrawGridLines(true);
        xAxis.setValueFormatter(new ValueFormatter() {
            @Override
            public String getFormattedValue(float value) {
                int seconds = (int) (value * samplePeriod);
                if (seconds < 60) {
                    return seconds + "s";
                } else {
                    int mins = seconds / 60;
                    int secs = seconds % 60;
                    return String.format("%d:%02d", mins, secs);
                }
            }
        });

        // 4. 配置Y轴
        YAxis leftAxis = chart.getAxisLeft();
        leftAxis.setAxisMinimum(0f);
        leftAxis.setAxisMaximum(160000f);
        leftAxis.setDrawGridLines(true);
        leftAxis.setValueFormatter(new ValueFormatter() {
            @Override
            public String getFormattedValue(float value) {
                return String.format("%.0f", value);
            }
        });

        YAxis rightAxis = chart.getAxisRight();
        rightAxis.setEnabled(false);

        // 5. 填充图表数据
        populateChartData();
    }

    private void populateChartData() {
        if (runDataList == null || runDataList.isEmpty()) {
            Log.e("FullScreenChart", "No data available for full screen chart");
            return;
        }

        // 按通道分组数据
        Map<Integer, List<Entry>> channelEntriesMap = new HashMap<>();
        for (int i = 0; i < 8; i++) {
            channelEntriesMap.put(i, new ArrayList<>());
        }

        // 填充数据
        for (RunData data : runDataList) {
            int channel = data.getChannel();
            float value = data.getValue();
            int generationCount = data.getGenerationCount();

            if (channel >= 0 && channel < 8) {
                List<Entry> entries = channelEntriesMap.get(channel);
                entries.add(new Entry(generationCount, value));
            }
        }

        // 创建数据集
        List<LineDataSet> dataSets = new ArrayList<>();
        for (int i = 0; i < 8; i++) {
            List<Entry> entries = channelEntriesMap.get(i);
            LineDataSet dataSet = new LineDataSet(entries, "通道 " + (i + 1));
            dataSet.setColor(channelColors[i]);
            dataSet.setLineWidth(2f);
            dataSet.setDrawCircles(true);
            dataSet.setDrawValues(false);
            dataSet.setVisible(true);
            dataSets.add(dataSet);
        }
        LineData lineData = new LineData();
        for (LineDataSet dataSet : dataSets) {
            lineData.addDataSet(dataSet);
        }
        // 设置图表数据
        chart.setData(lineData);

        // 刷新图表
        chart.getData().notifyDataChanged();
        chart.notifyDataSetChanged();
        chart.invalidate();
    }
}